<?php

namespace App\Http\Controllers\Merchant;

use App\Http\apiResponse;
use App\translate;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class TranslateController extends Controller
{
    use apiResponse;
    public $langs=[
        ['id'=>'en'],
        ['id'=>'spanish']
    ];
    public function index(Request $request)
    {
       $list=translate::when($request->get('keywords'),function ($query)use ($request){
           $query->where('code','like','%'.$request->get('keywords').'%')
               ->OrWhere('cont',"like",'%'.$request->get('keywords').'%')
               ->OrWhere('mark',"like",'%'.$request->get('keywords').'%');
       })->groupBy("code")->latest()->paginate($request->get('pageSize',10),'*','pageNo')->toArray();

       foreach ($list['data'] as $k=>&$v){
           $lists=translate::where('code',$v['code'])->get();
           $v[$v['lang']]=$v['cont'];

           foreach ($lists as $key=>$vv){
               $v[$vv['lang']]=$vv['cont'];
           }
           $v['lang_list']=$this->langs;
       }




       return response()->json(['code'=>200,'data'=>$list]);

    }

    public function createjs()
    {


        foreach($this->langs as $v){
            $nls=array();
            $ls=translate::where("lang",$v['id'])->get();
            foreach($ls as $vv){
                $nls[$vv['code']]=$vv['cont'];
            }
            $jsondata[$v['id']]=$nls;
        }

        file_put_contents('translate.js','var Translatedata='.json_encode($jsondata).";");
        return response()->json(['code'=>200,'msg'=>'success']);
    }
    public function store(Request $request)
    {
       $code=$request->get('code');
       if (!$code){
           $code=time();
       }
       $tid=0;
       foreach ($this->langs as $key=>$v){
           $data=[
               'code'=>$code,
               'lang'=>$v['id'],
               'cont'=>$request->get($v['id']),
               'mark'=>$request->get('mark')
           ];
           $create=translate::create($data);

       }
       return $this->resp_message(200,'add success');
    }
    public function update($code,Request $request)
    {
       foreach ($this->langs as $key=>$v){
           translate::where('code',$code)->where('lang',$v['id'])->update(['cont'=>$request->get($v['id']),'mark'=>$request->get('mark')]);
       }
       return $this->resp_message(200,'update success');
    }

}
